package com.mojo.jedis.controller;

import com.mojo.jedis.service.UserService;
import com.mojo.jedis.cache.UserCache;
import com.mojo.jedis.cache.VerificationCodeCache;
import com.mojo.jedis.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/9/27 16:58
 */
@RestController
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserCache userCache;
    @Autowired
    private VerificationCodeCache codeCache;
    @Autowired
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // keys命令组
    @GetMapping("testKeys")
    public void testKeys() {
        userCache.testRedisTemplate();
    }

    @GetMapping("redisString")
    public void redisString() {
        userCache.testRedis();
    }

    @GetMapping("redisList")
    public List<Object> redisList() {
        return userCache.testList();
    }

    @GetMapping("redisHash")
    public void redisHash() {
        userCache.testHash();
    }

    @GetMapping("redisSet")
    public void redisSet() {
        userCache.testSet();
    }

    @GetMapping("redisZset")
    public void redisZset() {
        userCache.testZset();
    }

    @GetMapping("redisHyper")
    public void redisHyperLogLog() {
        userCache.testHyperLogLog();
    }

    @GetMapping("sendCode")
    public String sendCode() {
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        codeCache.sendCode(code);
        return code;
    }

    @GetMapping("verify")
    public boolean verify(@RequestParam String code) {
        return codeCache.verify(code);
    }


    @PostMapping("user")
    public Boolean add(@RequestBody User user) {
        user.setTime(LocalDateTime.now());
        return userCache.cacheObject(user);
    }

    /**
     * 分布式锁设置值
     *
     * @author Mojo
     */
    @GetMapping("/distributeLock")
    public Boolean nxEx() {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        Boolean flag = operations.setIfAbsent("lock", "1", 50, TimeUnit.SECONDS);
        return flag;
    }
}
